assert(PandaDKP, "PandaDKP not found!")

------------------------------
--      Are you local?      --
------------------------------
local PandaDKP = PandaDKP
local Bidding =
{
   Items = {},
   Buttons = {},
}
PandaDKP.Bidding = Bidding




function Bidding:Enable()
end

function Bidding:BiddingOpen(auctioneer, link)
   -- Get more information about the item
   local name, _, quality, _, _,type, subtype, stackcount, _, texture = GetItemInfo(link)
   if name == nil then
      PandaDKP:Print(string.format("Invalid item link: %s", link))
      return false
   end
   
   -- Create the data we'll need in order to display it
   local info =
   {
      auctioneer = auctioneer,
      name = name,
      link = link,
      itemId = PandaDKP:ExtractItemID(link),
      class = type,
      subclass = subtype,
      quality = quality,
      colour = PandaDKP:rgbToHex(ITEM_QUALITY_COLORS[quality]),
      colourrgb = { r=ITEM_QUALITY_COLORS[quality].r, g=ITEM_QUALITY_COLORS[quality].g, b=ITEM_QUALITY_COLORS[quality].b },
      count = stackcount,
      texture = texture,
      my_bidstate = '',
      auc_bidstate = '',
   }
   tinsert(Bidding.Items, info)
   
   -- Get a reference to the GUI button that will display our item
   local button
   if (#(Bidding.Buttons) < #(Bidding.Items)) then
      -- Create a new loot button for the item
      button = Bidding:CreateButton(#(Bidding.Items))
   else
      -- We can re-use an existing button
      button = Bidding.Buttons[#(Bidding.Items)]
   end
   
   -- Set the button's item information
   Bidding:SetButtonInfo(button, info)
   
   -- Show the bidding window
   Bidding:ShowWindow()
end

function Bidding:BiddingClosed(auctioneer)
   Bidding:BiddingCanceled(auctioneer)
end

function Bidding:BiddingCanceled(auctioneer)
   Bidding.Items = {}
   PDKP_Bidding:Hide()
   
   for i=1, #(Bidding.Buttons) do
      Bidding.Buttons[i]:Hide()
   end
   
   -- !!! BUG !!!  If another auctioneer has items showing, they will be cleared too
end

function Bidding:BidAccepted(auctioneer, itemId, state)
   -- Find all items that match and mark their bid state
   for i=1, #(Bidding.Items) do
      if (Bidding.Items[i].auctioneer == auctioneer and Bidding.Items[i].itemId == itemId) then
         Bidding.Items[i].auc_bidstate = state
         Bidding:UpdateStatusText(i)
      end
   end
end




--------------------
--    UI CRAP     --
--------------------

function Bidding:ShowTooltip(button, id)
   GameTooltip:SetOwner(button, "ANCHOR_RIGHT")
   GameTooltip:SetHyperlink(Bidding.Items[id].link)
   GameTooltip:Show()
   if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
   CursorUpdate()
end

function Bidding:OnLootButtonClick(button, mouse, id)

   -- If its a ctrl-click, then show the item in dress up
   if (mouseButton == "LeftButton" and IsControlKeyDown()) then
      DressUpItemLink(Bidding.Items[id].link)
      return
   elseif (mouseButton == "LeftButton" and IsShiftKeyDown()) then
      ChatEdit_InsertLink(Bidding.Items[id].link)
      return
   end
   
end

function Bidding:OnRollButtonClick(button, mouse, id, roll)
   
   -- Bid on all items with that ID
   local itemId = Bidding.Items[id].itemId
   if (Bidding.Items[id].my_bidstate == roll) then
      -- If the roll is the same as the current bid, then UNBID
      PandaDKP.Comm:Send("WHISPER", string.format("UNBID %d", Bidding.Items[id].itemId), Bidding.Items[id].auctioneer)
   else
      PandaDKP.Comm:Send("WHISPER", string.format("BID %d %s", Bidding.Items[id].itemId, roll), Bidding.Items[id].auctioneer)
   end
   
   -- Mark all items with that item ID as pending
   for i=1, #(Bidding.Items) do
      if (Bidding.Items[i].itemId == itemId) then
         if (Bidding.Items[i].my_bidstate == roll) then
            Bidding.Items[i].my_bidstate = 'U'
         else
            Bidding.Items[i].my_bidstate = roll
         end
         Bidding:UpdateStatusText(i)
      end
   end
end

function Bidding:ShowWindow()
   -- Calculate the height of the window based on the items shown
   local height = 55 + (50 * #(Bidding.Items))
   PDKP_Bidding:SetHeight(height)
   PDKP_Bidding:Show()
end

function Bidding:CreateButton(id)
   local button = CreateFrame("Button", "PDKP_LootButton"..id, PDKP_Bidding, "PDKP_LootButtonTemplate")
   button:SetID(id)
   
   button:ClearAllPoints()
   button:SetPoint("TOPLEFT", PDKP_Bidding, "TOPLEFT", 10, -50 - (id-1)*(button:GetHeight()+ 5))
   
   button.lootButton = _G["PDKP_LootButton"..id.."LootButton"]
   button.itemname = _G["PDKP_LootButton"..id.."Text"]
   button.statusline = _G["PDKP_LootButton"..id.."Description"]
   button.statusicon = _G["PDKP_LootButton"..id.."Icon"]
   
   Bidding.Buttons[id] = button
   return button
end

function Bidding:SetButtonInfo(button, info)
   button.lootButton:SetNormalTexture(info.texture)
   button.itemname:SetTextColor(info.colourrgb.r, info.colourrgb.g, info.colourrgb.b)
   button.itemname:SetText(info.name)
   Bidding:UpdateStatusText(button:GetID())
   button:Show()
end

function Bidding:UpdateStatusText(id)
   local button = Bidding.Buttons[id]
   local info = Bidding.Items[id]
   
   -- Examples: Bid Pending    Bid Canceled    Bid Accepted    Canceling Bid    
   local text
   local texture
   if ('N' == info.my_bidstate) then
      texture = "Interface\\Buttons\\UI-GroupLoot-Dice-Up"
      if ('N' == info.auc_bidstate) then
         text = "Bid Accepted"
      else
         text = "Bid Pending"
      end
   elseif ('G' == info.my_bidstate) then
      texture = "Interface\\Buttons\\UI-GroupLoot-Coin-Up"
      if ('G' == info.auc_bidstate) then
         text = "Bid Accepted"
      else
         text = "Bid Pending"
      end
   elseif ('U' == info.my_bidstate) then
      if ('U' == info.auc_bidstate) then
         text = "Bid Canceled"
      elseif ('N' == info.auc_bidstate) then
         texture = "Interface\\Buttons\\UI-GroupLoot-Dice-Up"
         text = "Canceling Bid"
      elseif ('G' == info.auc_bidstate) then
         texture = "Interface\\Buttons\\UI-GroupLoot-Coin-Up"
         text = "Canceling Bid"
      else
         text = "Canceling Bid"
      end
   end
   
   if (text) then
      button.statusline:SetText(text)
   else
      button.statusline:SetText('')
   end
   
   if (texture) then
      button.statusicon:Show()
      button.statusicon:SetTexture(texture)
   else
      button.statusicon:Hide()
   end
end